<template>
    <el-dialog :close-on-click-modal="false"  ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="50%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <el-form-item label="设施类型" prop="facilityTypeName">
                <el-select :disabled="addEditFlag == 'lookView'" v-model="ruleForm.facilityTypeName" class="w100p"
                    clearable filterable placeholder="请选择设施类型">
                    <el-option v-for="item, index in facilityTypeList" :key="index" :label="item.facilityCategory"
                        :value="item.facilityCategory" @change="facilityCategory"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="养殖类型">
                <el-select :disabled="addEditFlag == 'lookView'" v-model="ruleForm.breedType" class="w100p" clearable
                    filterable placeholder="请选择养殖类型">
                    <el-option v-for="item, index in breedTypeList" :key="index" :label="item.name"
                        :value="item.breedType"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="设施编号" prop="facilityNo">
                <el-input :disabled="addEditFlag == 'lookView' || addEditFlag === 'edit'" v-model="ruleForm.facilityNo"
                    placeholder="请输入编号" clearable></el-input>
            </el-form-item>
            <el-form-item label="设施名称" prop="facilityName">
                <el-input :disabled="addEditFlag == 'lookView'" v-model="ruleForm.facilityName" placeholder="请输入设施名称"
                    clearable></el-input>
            </el-form-item>
            <el-form-item label="建立日期" prop="buildTime">
                <el-date-picker :disabled="addEditFlag == 'lookView'" v-model="ruleForm.buildTime"
                    value-format="yyyy-MM-dd" align="right" type="date" placeholder="选择日期"
                    :picker-options="pickerOptions" clearable>
                </el-date-picker>
            </el-form-item>
            <el-form-item label="设施面积" prop="scope">
                <el-input :disabled="addEditFlag == 'lookView'" type="number" v-model="ruleForm.scope"
                    placeholder="请输入设施面积"></el-input>
            </el-form-item>
            <el-form-item label="设施单位" prop="unitNo">
                <el-select :disabled="addEditFlag == 'lookView'" v-model="ruleForm.unitNo" style="width: 100%" clearable
                    filterable>
                    <el-option v-for="item in unitList" :key="item.unitNo" :label="item.unitName"
                        :value="item.unitNo" />
                </el-select>
            </el-form-item>
            <el-form-item label="设施造价" prop="facilityCost">
                <el-input :disabled="addEditFlag == 'lookView'" v-model.number="ruleForm.facilityCost"
                    placeholder="请输入设施造价" clearable>
                    <template slot="append">元</template>
                </el-input>
            </el-form-item>
            <el-form-item label="设施租金" prop="facilityRent">
                <el-input :disabled="addEditFlag == 'lookView'" v-model.number="ruleForm.facilityRent"
                    placeholder="请输入设施租金" clearable>
                    <template slot="append">元</template>
                </el-input>
            </el-form-item>
            <el-form-item label="设施位置" prop="cwhsmanagerName">
                <el-input :disabled="addEditFlag == 'lookView'" v-model="ruleForm.num" placeholder="请输入设施名称"></el-input>
            </el-form-item>
            <el-form-item label="经纬度">
                <span class="axis">经度：{{ ruleForm.axisY || '--' }}</span>
                <span class="axis">纬度：{{ ruleForm.axisX || '--' }}</span>
            </el-form-item>
            <el-form-item label="设施划分">
                <el-button @click="mapVisible = true">{{ addEditName }}区域</el-button>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
        <Map :isShowCloseBtn="isShowCloseBtn" :facilityId="facilityId" :mapVisible="mapVisible"
            :initPolygon="facilityPointList" @closeMapDialog="closeMapDialog"></Map>
    </el-dialog>
</template>
<script>
import UnitManage from '@/api/basicInformation/unitManage.js';
import facilityManagement from '@/api/digtalOperation/facilityManagement';
import Map from './map';
// queryFacilityType
export default {
    components: { Map },
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        facilityTypeList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        var validatefacilityNo = (rule, value, callback) => {
            if (!value) {
                callback(new Error("设施编号不能为空"));
            } else {
                var patrn = /[`~!@#$%^&*()\+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）={}|《》？：“”【】、；‘'，。、]/im;
                if (patrn.test(value)) {
                    callback(new Error("编号不能包含 $、&、￥等特殊字符"));
                } else {
                    callback();
                }
            };
        };
        var validateNumber = (rule, value, callback) => {
            if (value && Number(value) < 0) {
                callback(new Error("请输入大于0的数值"));
            } else {
                callback();
            }
        };
        return {
            breedTypeList: [
                {
                    name: "吊水养殖",
                    breedType: "HANGING_WATER_BREED"
                },
                {
                    name: "传统养殖",
                    breedType: "TRADITION_BREED"
                },
                {
                    name: "循环水养殖",
                    breedType: "CIRCULATE_BREED"
                },
                {
                    name: "跑道养殖",
                    breedType: "RUNWAY_BREED"
                }
            ],
            isShowCloseBtn: true,
            addEditName: '添加',
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            facilityPointList: [],
            mapVisible: false,
            addEditApi: facilityManagement.add,
            ruleForm: {},
            unitList: [],
            facilityId: '',
            rules: {
                facilityTypeName: [
                    { required: true, message: "请选择设施类型", trigger: "change" }
                ],
                facilityName: [
                    { required: true, message: "请输入设施名称", trigger: "blur" }
                ],
                facilityNo: [
                    { required: true, validator: validatefacilityNo, trigger: "blur" }
                ],
                facilityCost: [
                    { validator: validateNumber, trigger: "blur" }
                ],
                facilityRent: [
                    { validator: validateNumber, trigger: "blur" }
                ],
                scope: [
                    { validator: validateNumber, trigger: "blur" }
                ],

                breedType: [
                    { required: true, message: "请选择类型", trigger: "change" }
                ],
            }
        }
    },
    computed: {
        person() {
            return this.$store.state.initData.person || [];
        },
        stordoc() {
            return this.$store.state.initData.stordoc || [];
        },
        lessesList() {
            return this.$store.state.initData.lessesList || [];
        }
    },
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },
    async mounted() {
        const { data: res } = await UnitManage.getallBasicunitlist({
            unitTypeNo: "995416636939862016"
        });
        this.unitList = res;
    },
    methods: {
        async initData() {
            this.facilityPointList = [];
            this.facilityId = -1;
            if (this.addEditFlag == 'add') {
                this.resetForm()
                this.addEditApi = facilityManagement.add
                this.addEditName = '添加'
                this.isShowCloseBtn = true;
            } else if (this.addEditFlag == 'edit' || this.addEditFlag == 'lookView') {
                this.ruleForm = { ...this.data }
                this.addEditApi = facilityManagement.edit
                this.facilityCategory(this.ruleForm.facilityCategory);
                this.addEditName = this.addEditFlag == 'lookView' ? '查看' : '编辑';
                this.isShowCloseBtn = this.addEditFlag == 'lookView' ? false : true;

                let { data } = await facilityManagement.queryFacilityArea(this.ruleForm.facilityNo);
                this.facilityPointList = data ? data.facilityPointList : [];
                this.facilityId = data ? Number(data.facilityId) : -1;
                this.ruleForm.axisX = this.getCenterPoint(this.facilityPointList).axisX;
                this.ruleForm.axisY = this.getCenterPoint(this.facilityPointList).axisY;
            }
        },
        getCenterPoint(data) {
            console.log(data)
            let lng = 0.0;
            let lat = 0.0;
            for (let point of data) {
                lat += Number(point["axisX"]);
                lng += Number(point["axisY"]);
            }
            lng = lng / data.length + 0.000084;
            lat = lat / data.length + 0.000014;
            console.log({ axisY: lng, axisX: lat })
            return { axisY: lng, axisX: lat };
        },
        facilityCategory(val) {
            if (this.facilityTypeList) {
                this.facilityTypeList.forEach(item => {
                    if (val === item.facilityCategory) {
                        this.ruleForm.facilityTypeNo = item.facilityTypeNo;
                    }
                });
            }
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                console.log(this.ruleForm)
                if (valid) {
                    this.addEditApi({
                        ...this.ruleForm,
                        systemNo: sessionStorage.systemNo,
                        farmingTypeNo: sessionStorage.farmingTypeNo,
                    }).then(res => {
                        if (res.code == 1) {
                            this.$message.success('操作成功')
                        } else {
                            this.$message.warning(res.msg || '操作失败')
                        }
                        this.$store.dispatch('initData/queryAllFacilityDetail');
                        this.cancel()
                    }).catch(err => {
                        console.log(err)
                        this.$message.warning(err || '操作失败')
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        closeMapDialog(list) {
            this.mapVisible = false;
            this.facilityPointList = list;
            this.ruleForm.axisX = this.getCenterPoint(this.facilityPointList).axisX;
            this.ruleForm.axisY = this.getCenterPoint(this.facilityPointList).axisY;
            this.$set(this.ruleForm, 'facilityPointList', list)
            console.log(list)
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.axis {
    display: inline-block;
    padding: 0 20px;
}
</style>